import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入登录组件
import Login from '../views/Login.vue'
// 导入主界面
import Home from '../views/Home.vue'
// 导入欢迎页
import Welcome from '../views/Welcome.vue'
// 导入User页面
// @表示src目录
import User from '@/views/User/User.vue'
// 导入权限页面
import Right from '@/views/Power/Right.vue'
// 导入权限管理页面
import Role from '@/views/Power/Role.vue'
// 导入商品分类页面
import Category from '@/views/Good/Category.vue'
// 导入分类参数页面
import Param from '@/views/Good/Params.vue'
// 导入商品详情页
import GoodList from '@/views/Good/GoodList.vue'
// 导入添加商品页面
import AddGood from '@/views/Good/AddGood.vue'
// 导入订单页面
import OrderList from '@/views/Order/OrderList.vue'
// 导入报告页面
import Report from '@/views/Report/Report.vue'
Vue.use(VueRouter)
const routes = [
  // 路由重定向
  { path: '/', redirect: '/login' },
  // 配置登录路由规则
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: User },
      { path: '/rights', component: Right },
      { path: '/roles', component: Role },
      { path: '/categories', component: Category },
      { path: '/params', component: Param },
      { path: '/goods', component: GoodList },
      { path: '/goods/addgoods', component: AddGood },
      { path: '/orders', component: OrderList },
      { path: '/reports', component: Report }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由的导航守卫
router.beforeEach((to, from, next) => {
  // to指代你要跳转到的页面
  // from 指代你从哪里过来
  // next强制跳转到哪里，或者指代直接放行

  // 1、如果你是去登陆界面，直接放行
  if (to.path === '/login') return next()

  // 2、先获取会话端的token，如果存在直接放行，如果不存在那么就强制跳转到登陆界面
  const myToken = window.sessionStorage.getItem('token')
  if (!myToken) return next('/login')
  next()
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
